/**
 * Created by Administrator on 2017/5/10 0010.
 */
import React from "react";
import Relay from "react-relay";
import { Input, Select } from 'antd';
import TotalCount from "./TotalCount"
import TotalCountChinese from "./TotalCountChinese"
import Createorder_DetailItem_Yarn from "./Createorder_DetailItem_Yarn";
import ReactKey from "../../../util/ReactKey"
import GetParentOrderMutation from "../mutation/GetParentOrderMutation";
import GetOrderByTraffickerMutation from "./mutation/GetOrderByTraffickerMutation";
const Option = Select.Option;
import Config from "../../../util/Config"
export default class CreactStepOneYarn extends React.Component{
    constructor(props){
        super(props);
        this.state ={
            goods:[],
            num: 0,
            partAName: '',
            account: '',
            parentId:'',
            isSelect: 0,
            value: '请选择上游订单'
        }
        this.goods = [{}, {}, {}];
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.serviceType = sessionStorage.getItem('serviceType');
    }

    componentWillMount(){
        this.state.num = this.goods.length;
        this.setState({
            goods: this.goods,
        });
        this.upOrderList()
    }

    repalceitem(context, index) {
        let goods = this.state.goods;
        goods.splice(index, 1, context);
        this.setState({
            goods: goods
        });
    }

    setcountcallback(){
        let total = 0;
        let totalmoney=0;
        this.state.goods.map((context,index)=>{
            let quantity = this.refs['creatorderditem'+index].state.context.quantity;
            let price = this.refs['creatorderditem'+index].state.context.price;
            if(quantity){
              total += Number(quantity);
              // total = Math.ceil(total);
              // console.log(total);
            }
            if(quantity&&price){
                let temptotal = Number(quantity)*Number(price)
                // if(!isNaN(totalmoney)){
                totalmoney = parseFloat(totalmoney)+temptotal;
                totalmoney = parseFloat(totalmoney).toFixed(2);
                // }
            }
        });
        this.refs.totalcount.setState({
            quantity:total.toFixed(3),
            totalprice:totalmoney
        });
        this.refs.totalcountchinese.setState({
            count:totalmoney,
        });
    }

    showimgmodal(index,){
        this.props.showimgmodal(index,this.state.goods[index].url)
    }

    additemlist() {
        let goods = this.state.goods;
        goods.push({});
        this.setState({
            goods: goods
        });

    }
    delteitem(index) {
        let goods = this.state.goods;
        goods.splice(index, 1);
        this.setState({
            goods: goods
        },()=>{
            this.setcountcallback();
        });
    }
    additem() {
        return this.state.goods.map((context, index)=> {
            let isshow = true
            return (
                <Createorder_DetailItem_Yarn context={context} index={index} key={ReactKey.key}
                                             additemlist={this.additemlist.bind(this)}
                                             delteitem={this.delteitem.bind(this)}
                                             totallenght={this.state.goods.length}
                                             repalceitem={this.repalceitem.bind(this)}
                                             isshow={isshow}
                                             showimgmodal = {this.showimgmodal.bind(this)}
                                             ref={'creatorderditem'+index}
                                             setcountcallback = {this.setcountcallback.bind(this)}
                />
            );
        });
    }
    addfrom(){
        return(
            <div className="order_form_total_div">
                <span className="order_form_top_span">
                </span>
                <table className="order_form_table">
                    <thead>
                    <tr className="order_from_tr">
                        <td className="order_frorm_td order_from_td_num order_detail_thead_style"/>
                        <td className="order_frorm_td order_from_td_snum order_detail_thead_style">款号</td>
                        <td className="order_frorm_td order_from_td_cnum order_detail_thead_style">品名</td>
                        <td className="order_frorm_td order_from_td_describe order_detail_thead_style">描述/规格</td>
                        <td className="order_frorm_td order_from_td_snum order_detail_thead_style">纱线类型</td>


                        <td className="order_frorm_td order_from_td_snum order_detail_thead_style">成纱状态</td>
                        <td className="order_frorm_td order_from_td_describe order_detail_thead_style">成分</td>
                        <td className="order_frorm_td order_from_td_color order_detail_thead_style">纱支</td>
                        
                        
                        <td className="order_frorm_td order_from_td_monad order_detail_thead_style">单位</td>

                        <td className="order_frorm_td order_from_td_pnum order_detail_thead_style"><span style={{color:'red'}}>*</span>数量</td>
                        <td className="order_frorm_td order_from_td_ucost order_detail_thead_style"><span style={{color:'red'}}>*</span>单价</td>

                        <td className="order_frorm_td order_from_td_monad order_detail_thead_style">金额</td>
                        
                        
                        <td className="order_frorm_td order_from_td_moeny order_detail_thead_style">备注</td>
                        <td className="order_frorm_td order_from_td_delandadd order_detail_thead_style"/>
                    </tr>
                    </thead>
                    {
                        this.additem()
                    }

                    <TotalCount ref={'totalcount'} type={'yarn'}/>

                    <TotalCountChinese ref={"totalcountchinese"} type={'yarn'}/>

                </table>

            </div>
        );
    }
    _DownLodaExcel(){
        window.location.href = Config.qiuniu+'%E7%BA%B1%E7%BA%BF%E6%A8%A1%E6%9D%BF.xlsx';
    }
    _ToLeadExcel(){
        this.props.ToLeadExcel();
    }
    toLeadExcel(orders){
        if(orders.length==0){

        }else{
            let goods = this.state.goods;
            let goodstest = [];
            let addindex = [];
            goods.map((context,index)=>{
                let values = Object.values(context);
                if(values.length!=0){
                    addindex.push(index)
                }
            });
            addindex.map((context)=>{
                goodstest.push(goods[context])
            });

            let tgoods = goodstest.concat(orders);
            this.setState({
                goods: tgoods
            },()=>{
                this.setcountcallback();
            });
        }
    }
    showlibrary() {
        this.props.ShowLibrary();
    }
    addModalfromlist(orders) {
        if(orders.length==0){

        }else{
            let goods = this.state.goods;
            let goodstest = [];
            let addindex = [];
            goods.map((context,index)=>{
                let values = Object.values(context);
                if(values.length!=0){
                    addindex.push(index)
                }
            });
            addindex.map((context)=>{
                goodstest.push(goods[context])
            });

            let tgoods = goodstest.concat(orders);
            this.setState({
                goods: tgoods
            });
        }
    }
    setgoodsimg(url,index){
        if(!url){
            Modal.warning({
                title: '图片',
                content: '请选择图片',
            });
            return;
        }
        if(index+1){
            let goods = this.state.goods
            goods[index].url = url;
            this.setState({
                goods:goods
            });
        }else{
        }
    }

    handleChange(Index) {
        let partAName = this.state.partAordlist[Index].partAName;
        let partBName = this.state.partAordlist[Index].partBName;
        let account = this.state.partAordlist[Index].account;
        let oid = this.state.partAordlist[Index].oid;
        this.serviceType == 6 ? (
            this.setState({
                partAName: partBName,
                account: Number(account/100).toFixed(2),
                parentId: oid,
                isSelect: 1,
                value: oid
            })
        ): (
            this.setState({
                partAName: partAName,
                account: Number(account/100).toFixed(2),
                parentId: oid,
                isSelect: 1,
                value: oid
            })
        )
    }
    upOrderList() {
      if(this.serviceType == 6){
          /*贸易商-创建布料、辅料订单*/
          Relay.Store.commitUpdate(
              new GetOrderByTraffickerMutation({
                  enId : this.enterpriseId
              }),
              {
                  onFailure: () => {

                  },
                  onSuccess: (response) => {
                      let errorCode = response.getOrderByTrafficker.getOrderByTrafficker.errorCode;
                      if(errorCode==0){
                          let orders = response.getOrderByTrafficker.getOrderByTrafficker.orders;
                          this.setState({
                              partAordlist: orders
                          });
                      }
                  }
              }
          )
      } else {
        Relay.Store.commitUpdate(
            new GetParentOrderMutation({
                enId : this.enterpriseId
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.getParentOrder.getParentOrder.errorCode;
                    if(errorCode==0){
                        let orders = response.getParentOrder.getParentOrder.orders;
                        this.setState({
                            partAordlist: orders
                        });
                    }
                }
            }
        )
      }
    }

    render(){
        return (
            <div>
                <span
                    ref={'enterpriseList'}
                    className="create_order_select" style={{marginLeft:'20px',color:'#333',fontSize:'14px'}}><b style={{color: 'red'}}>*</b>{this.serviceType == 6 ? '成衣订单:' : '上游订单:'}&nbsp;
                    <Select
                        getPopupContainer={()=>this.refs.enterpriseList}
                        notFoundContent="没有找到相关订单"
                        className="order_creat_select"
                        dropdownClassName="order_creat_select_drop"
                        value={this.state.value}
                        defaultValue={this.state.value}
                        style={{ width: 220 }}
                        onChange={this.handleChange.bind(this)}>
                            {this.state.partAordlist ? this.state.partAordlist.map((v,i)=>{
                                return <Option key={v.oid} value={i}>{v.oid}</Option>
                            }) : null}
                    </Select>
                    <span style={this.state.isSelect ? {display:'inline-block'}:{display:'none'}} className="create_order_download_title">客户: {this.state.partAName}</span>
                    <span style={this.state.isSelect ? {display:'inline-block'}:{display:'none'}} className="create_order_download_title">订单金额: {this.state.account}</span>
                </span>
                <p className="create_order_download">
                    <span style={{marginLeft:'-20px',color:'#333',fontSize:'14px'}} className="create_order_download_title">币种: 人民币</span>
                    <a className="create_order_download_download" onClick={this._DownLodaExcel.bind(this)}>下载excel导入模板</a>
                    <a className="create_order_download_goods" onClick={this._ToLeadExcel.bind(this)}>excel导入商品</a>
                    {/*
                     <span className="create_order_excel_in" onClick={this.showlibrary.bind(this)}>+从商品库选择</span>
                     */}
                </p>
                {
                    this.addfrom()
                }
            </div>
        )
    }
}
